package com.luom.springbootinit.job.cycle;

import com.luom.springbootinit.model.entity.BorrowRecord;
import com.luom.springbootinit.service.BorrowRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class UpdateBrStatus {

    @Resource
    private BorrowRecordService borrowRecordService;

    @Scheduled(cron = "0 37 16 * * ?")
    public void updateBrStatus() {
        log.info("定时任务已运行");
        List<Integer> ids = borrowRecordService.query()
                .eq("brStatus", "borrowed")
                .list()
                .stream()
                .filter(borrowRecord -> {
                    long createTimeMillis = borrowRecord.getCreateTime().getTime();
                    long nowTimeMillis = System.currentTimeMillis();
                    long daysBorrowed = (nowTimeMillis - createTimeMillis) / (24 * 60 * 60 * 1000);
                    return daysBorrowed > 7 && "borrowed".equals(borrowRecord.getBrStatus());
                })
                .map(BorrowRecord::getId)
                .collect(Collectors.toList());
        if (!ids.isEmpty()) {
            int count=borrowRecordService.updateBatchStatus(ids);
            log.info("已更新" + count + "条数据状态为已超期");
        }
    }
}
